﻿using System;
using System.Threading;
using System.Threading.Tasks;
using opensj;

namespace opensj
{
    public abstract class ThreadEX
    {
        private enum ThreadStatus : int
        {
            Thread_Wait = 0,
            Thread_Run,
            Thread_asyncRun,
            Thread_Pasue,
            Thread_Exit,
        }
        private ThreadStatus _status;
        private Thread _thread;
        private void TaskEx()
        {
            while (_status != ThreadStatus.Thread_Exit)
            {
                switch (_status)
                {
                    case ThreadStatus.Thread_Run:
                        OnRun();
                        break;
                    case ThreadStatus.Thread_Pasue:
                        OnPasue();
                        break;
                    case ThreadStatus.Thread_asyncRun:
                        Task.Run(async () => await OnasyncRun()).Wait();
                        break;
                }
                Thread.Sleep(m_ThreadSleep);
            }
        }
        public string m_ThreadName;
        public int m_ThreadSleep = 5;
        public ThreadEX()
        {
            _status = ThreadStatus.Thread_Wait;
        }

        public virtual void Start()
        {
            _thread = new Thread(TaskEx);
            _thread.Name = m_ThreadName;
            _thread.Priority = ThreadPriority.Normal;
            _thread.Start();
        }
        public virtual void Exit()
        {
            _status = ThreadStatus.Thread_Exit;
            if (_thread != null && _thread.IsAlive)
            {
                _thread.Join(); // 等待线程退出
                _thread = null;
            }
        }
        public virtual void Run() => _status = ThreadStatus.Thread_Run;
        public virtual void Pasue() => _status = ThreadStatus.Thread_Pasue;
        public virtual void asyncRun() => _status = ThreadStatus.Thread_asyncRun;

        public virtual void OnRun() { }

        public virtual void OnPasue() { }

        public virtual async Task OnasyncRun() { }
       
    }
}

